package com.yfbao.horizon.schedule.tk.front2;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.lang.instrument.Instrumentation;
import java.nio.charset.StandardCharsets;
import cn.hutool.json.JSONUtil;

public class MemoryCalculator {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object obj) {
        if (instrumentation == null) {
            throw new IllegalStateException("Instrumentation not initialized");
        }
        return instrumentation.getObjectSize(obj);
    }

    public static long getSerializedSize(Object obj) {
        // 尝试以 JSON 形式计算 UTF-8 字节长度（适用于非 Serializable 对象）
        try {
            String json = JSONUtil.toJsonStr(obj);
            return json.getBytes(StandardCharsets.UTF_8).length;
        } catch (Throwable ignore) {
            // ignore and fallback to native serialization below
        }

        // 回退到 JDK 序列化（对象需实现 java.io.Serializable）
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(obj);
            oos.flush();
            return baos.size(); // 避免额外数组拷贝
        } catch (Exception e) {
            return -1;
        }
    }
}
